import { createElement } from './Util';
import ErTableField from './ErTableField';
import ErBase from './ErBase';
import { nextTick,render } from 'vue';
import { ElIcon } from 'element-plus';
class ErTable extends ErBase {
  constructor(options, er) {
    super();
    this.type = 'ErTable';
    this.er = er;
    this.id = options.id;
    this.fields = [];
    this.options = options;
    this.createEl();
    this.updateName();
    this.updatePos(options.top, options.left);
    options.fields.forEach(f => this.addField(f,er.options.appContext));
  }

  createEl() {
    this.el = createElement('div', {
      'data-id': this.id,
      class: 'er-table',
    });
    this.elHeader = createElement('div', {
      class: 'er-table-header',
    });

    this.elBody = createElement('div', {
      class: 'er-table-body',
    });
    var newUL = document.createElement('ul');
    newUL.className = 'er-contextmenu'
    newUL.id = this.id
    // 创建一些li元素
    var newLI = document.createElement('li');
    newLI.addEventListener('click', (e)=>{
      this.er.removeTable(this.id)
    });
    newLI.textContent = '删除';
    newUL.appendChild(newLI);
    // 将自定义菜单添加到页面
    this.el.appendChild(newUL);
    this.el.appendChild(this.elHeader);
    this.el.appendChild(this.elBody);

    
    this.el.querySelector('.er-table-body').addEventListener('scroll', (e) => {
      this.er.repaint();
    });
    this.el.addEventListener('contextmenu', (event)=> {
      // 阻止默认的右键菜单
      event.preventDefault();
      // 创建自定义菜单的HTML
    // 定位自定义菜单
    let newUL = document.getElementById(this.id);
    newUL.style.display  = 'block'
    newUL.style.left = event.clientX + 'px';
    newUL.style.top = event.clientY + 'px';
    //FIX 右键菜单边缘化位置处理
    nextTick(() => {
      if (document.body.offsetWidth - event.clientX < this.el.offsetWidth) {
        newUL.style.left = document.body.offsetWidth - this.el.offsetWidth + 1;
        newUL.style.top =  event.clientY + 1;
      }
    });
    document.onclick = ()=>{
      var contextmenu = document.getElementById(this.id);
      if(contextmenu){
        contextmenu.style.display = "none";
      }
  };
    });

  }

  updateName() {
    this.elHeader.innerText = this.options.name;
  }

  updatePos(top, left) {
    this.top = top;
    this.left = left;
    this.el.style.top = top + 'px';
    this.el.style.left = left + 'px';
  }

  addField(field,appContext) {
    let erField = new ErTableField(field, this,appContext);
    this.fields.push(erField);
    this.elBody.appendChild(erField.el);
  }

  findField(id) {
    return this.fields.find(f => f.id == id);
  }

  remove() {
    this.er.removeTableLines(this.id);
    this.el.parentElement.removeChild(this.el);
  }

  toJSON() {
    return Object.assign({}, this.options, {
      fields: this.fields.map(f => f.toJSON()),
    });
  }

}

export default ErTable;
